package com.wang.example.netty.handler.client;

import com.wang.basic.netty.handler.Message;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.Scanner;

public class EchoClient {

    private final int port;
    private final String host;
    private Channel channel;
    private EventLoopGroup group;
    private Bootstrap b;

    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
        //客户端启动辅助类
        b = new Bootstrap();
        //构建线程组 处理读写
        group = new NioEventLoopGroup();
        b.group(group)
                //指明使用NIO进行网络通讯
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //出站处理器 先注册后执行
                        ch.pipeline().addLast(new EchoClientOutHandler1());
                        ch.pipeline().addLast(new EchoClientOutHandler2());

                        //入站处理器 先注册先执行
                        ch.pipeline().addLast(new EchoClientInHandler1());
                        ch.pipeline().addLast(new EchoClientInHandler2());


                    }
                });
    }

    public void start() {
        try {
            //连接到远程节点，阻塞等待直到连接完成
            ChannelFuture f = b.connect(new InetSocketAddress(host, port)).sync();
            //同步获取channel（通道，实际上是对socket的封装支持读取和写入）
            channel = f.sync().channel();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送消息
     * @param msg
     * @return
     */
    public boolean send(String msg) {
        Message message = new Message();
        message.setContent(msg);
        channel.writeAndFlush(message);
        return true;
    }

    /**
     * 关闭释放资源
     */
    public void close(){
        try {
            if (group != null)
            group.shutdownGracefully().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        EchoClient client = new EchoClient("127.0.0.1", 9999);
        try {
            client.start();
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String msg = scanner.next();
                client.send(msg);
            }
        }finally {
            client.close();
        }

    }
}
